package com.lindroy.androidplayer.viewmodels

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.lindroy.androidplayer.logic.model.BannerResp
import com.lindroy.androidplayer.logic.network.repository.Repository
import com.lindroy.androidplayer.utils.mapArticleData
import com.lindroy.androidplayer.utils.mapItem
import com.lindroy.androidplayer.utils.mapSingle
import kotlinx.coroutines.flow.Flow

/**
 * @author Lin
 * @date 2022/1/7
 * @function
 */
class HomeViewModel : PageViewModel() {

    private val _bannerLiveData = MutableLiveData<Unit>()

    private val _bannerItemClickAction = MutableLiveData<BannerViewModel>()

    private val _showBanner = MutableLiveData(false)

    private val articleItemClickAction = MutableLiveData<ArticleItemViewModel>()

    val articleItemClickLiveData = articleItemClickAction.mapSingle { it }

    val bannerLiveData = _bannerLiveData.switchMap { Repository.getBanner() }

    val articleListData: Flow<PagingData<ArticleItemViewModel>>
        get() = Repository.homeArticle.mapArticleData(articleItemClickAction)
            .cachedIn(viewModelScope)

    val bannerItemClickAction = _bannerItemClickAction.mapSingle { it }

    fun getBanner() {
        _bannerLiveData.postValue(Unit)
    }

    fun transBannerList(list: List<BannerResp>) =
        list.map { BannerViewModel(it.id, it.title, it.imagePath, it.url, _bannerItemClickAction) }
            .apply { _showBanner.value = isNotEmpty() }

}